/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package layoutitems;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

/**
 *
 * @author ST
 */
public class CurrentLayoutElements {
    
    //############################
    //      Fields                  
    //############################

    public static FileWriter out;
    public static ArrayList<ImageElement> allVisibleLayoutElements;

    //############################
    //      Methods                  
    //############################
    
    public static void writeCurrentLayoutToXml(String path, String fileName) throws IOException {
        out = new FileWriter(new File(path, fileName), false);
        out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n");
        int i = 0;
        for (Iterator<ImageElement> it = CurrentLayoutElements.allVisibleLayoutElements.iterator(); it.hasNext();) {    
            ImageElement item = it.next();
            out.write(item.writeCurrentLayoutElementAsXml(i));
             i++;
        }
        out.write("</root>");
        out.close();
    }

    public static boolean deleteLayoutItem(ImageElement deleteElement) {
        //System.out.println(deleteElement.writeLayoutElementAsXml());
        boolean foundDeleteItem = checkIfItemIsInViewArray(deleteElement);
        if (foundDeleteItem) {
            allVisibleLayoutElements.remove(allVisibleLayoutElements.indexOf(deleteElement));
        }
        return foundDeleteItem;
    }

    public static boolean moveItemUp(ImageElement moveUpElement) {
        boolean foundMoveUpItem = checkIfItemIsInViewArray(moveUpElement);
        int index = allVisibleLayoutElements.indexOf(moveUpElement);
        if (index < (allVisibleLayoutElements.size() - 1)) {
            Collections.swap(allVisibleLayoutElements, index, index + 1);
        }
        return foundMoveUpItem;
    }

    public static boolean moveItemDown(ImageElement moveDownElement) {
        boolean foundMoveDownItem = checkIfItemIsInViewArray(moveDownElement);
        int index = allVisibleLayoutElements.indexOf(moveDownElement);
        if (index > 0) {
            Collections.swap(allVisibleLayoutElements, index, index - 1);
        }
        return foundMoveDownItem;
    }

    private static boolean checkIfItemIsInViewArray(ImageElement checkElement) {
        boolean itemFound = false;
        for (ImageElement it : allVisibleLayoutElements) {
            if (it.equals(checkElement)) {
                itemFound = true;
            }
        }
        return itemFound;
    }
}
